<?php

namespace Wilead\ApiBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use Wilead\IArtistBundle\Entity\Chat;
use JPush\Model as M;
use JPush\JPushClient;
use JPush\Exception\APIConnectionException;
use JPush\Exception\APIRequestException;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ChatController
 *
 * @author jack
 */
class ChatController extends ApiController
{

    /**
     * @ApiDoc(
     *      description="发送聊天信息接口"
     * )
     * @RequestParam(name="uid", requirements="integer", description="发送者ID")
     * @RequestParam(name="fid", requirements="integer", description="接收者ID")
     * @RequestParam(name="type", requirements="string", description="信息类型（text文字信息,voice语音信息,image图片,video视频,file文件）")
     * @RequestParam(name="content", requirements="string", description="信息内容")
     * @RequestParam(name="extension", requirements="extension", description="扩展字段（非必须）")
     */
    public function sendAction(Request $request)
    {
        $chat = new Chat();
        $chat->setUid($request->request->get('uid'));
        $chat->setFid($request->request->get('fid'));
        $chat->setType($request->request->get('type'));
        $chat->setContent($request->request->get('content'));

        if ($request->request->has('extension')) {
            $chat->setExtension($request->request->get('extension'));
        }

        try {
            $client = new JPushClient('13fab03e3c235eba3f7c4205', 'c38c1917e44634808f0f8dc4');
            if ($chat->getType() == 'notice') {
                $client
                    ->push()
                    ->setPlatform(M\all)
                    ->setAudience(M\all)
                    ->setNotification(M\notification($chat->getContent()))
                    ->send();
            } else {
                $em = $this->getEntityManager();
                $em->persist($chat);
                $em->flush();

                $client
                    ->push()
                    ->setPlatform(M\all)
                    ->setAudience(M\audience(array('alias' => array($chat->getFid()))))
                    ->setNotification(array(
                        'ios' => array(
                            'alert' => $chat->getContent(),
                            'extras' => array(
                                'uid' => $chat->getUid(),
                                'fid' => $chat->getFid(),
                                'mtype' => $chat->getType()
                            )
                        ),
                        'android' => array(
                            'alert' => $chat->getContent(),
                            'extras' => array(
                                'uid' => $chat->getUid(),
                                'fid' => $chat->getFid(),
                                'mtype' => $chat->getType()
                            )
                        )
                    ))
                    ->send();

                $client
                    ->push()
                    ->setPlatform(M\all)
                    ->setMessage(M\message($chat->getContent(), null, null, array(
                        'uid' => $chat->getUid(),
                        'fid' => $chat->getFid(),
                        'mtype' => $chat->getType()
                    )))
                    ->send();
            }
        } catch (\Exception $e) {
            throw $e;
        }

        $view = $this->getFOSView();
        $view->setStatusCode(200)->setData($chat);
        return $view;
    }

    /**
     * @ApiDoc(
     *      description="获取聊天信息接口",
     *      filters={
     *          {"name"="limit", "dataType"="integer"},
     *          {"name"="lastDateTime", "dataType"="datetime", "pattern"="1988-01-01 08:23:54"},
     *          {"name"="firstDateTime", "dataType"="datetime", "pattern"="1988-01-01 08:23:54"}
     *      }
     * )
     */
    public function getAction($uid, $fid)
    {
        $repository = $this->getRepository('WileadIArtistBundle:User');

//        if (!$repository->isFriends($uid, $fid)) {
//            return $this->getFOSView()->setStatusCode(403)->setData('您和对方未确立好友关系，无法发起聊天，请先添加好友');
//        }
        // 设置已读
        $updateQb = $this->getEntityManager()->createQueryBuilder();
        $updateQb
            ->update('WileadIArtistBundle:Chat', 'q')
            ->set('q.readed', TRUE)
            ->where('q.fid = :rid')
            ->setParameter('rid', $uid)
            ->getQuery()
            ->execute();

        /* @var $qb \Doctrine\ORM\QueryBuilder */
        $qb = $this->getEntityManager()->getRepository('WileadIArtistBundle:Chat')->createQueryBuilder('q');
        $qb
            ->where('(q.uid = :uid AND q.fid = :fid) OR (q.uid = :fid AND q.fid = :uid)')->setParameters(array('uid' => $uid, 'fid' => $fid))
            ->orderBy('q.id', 'DESC');

        if ($this->getRequest()->query->has('limit')) {
            $qb->setMaxResults($this->getRequest()->query->get('limit'));
        }

        if ($this->getRequest()->query->has('lastDateTime')) {
            $qb->andWhere('q.created > :last')->setParameter('last', $this->getRequest()->query->get('lastDateTime'));
        }

        if ($this->getRequest()->query->has('firstDateTime')) {
            $qb->andWhere('q.created < :last')->setParameter('last', $this->getRequest()->query->get('firstDateTime'));
        }

        $result = $qb->getQuery()->getResult();

        $view = $this->getFOSView();
        return $view->setStatusCode(200)->setData($result);
    }

    /**
     * @ApiDoc(
     *      description="获取未读信息列表"
     * )
     */
    public function getNoReadedChatAction($id)
    {
        $qb = $this->getRepository('WileadIArtistBundle:Chat')->createQueryBuilder('q');
        $chat = $qb
            ->select('q, count(q.id) AS total')
            ->where('q.fid = :uid')->setParameter('uid', $id)
            ->andWhere('q.readed = FALSE')
            ->groupBy('q.uid')
            ->orderBy('q.created', 'DESC')
            ->getQuery()
            ->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);

        foreach ($chat as &$v) {
            $v['user'] = $this->getRepository('WileadIArtistBundle:User')->createQueryBuilder('q')->where('q.id = :id')->setParameter('id', $v['0']['uid'])->getQuery()->getSingleResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
        }
        $view = $this->getFOSView();
        return $view->setStatusCode(200)->setData($chat);
    }

}

?>
